<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>D3 Demo</title>
  <script src="https://d3js.org/d3.v6.min.js"></script>
  <style>
    .axis path,
    .axis line {
        fill: none;
        stroke: black;
        shape-rendering: crispEdges;
    }

    .axis text {
        font-family: sans-serif;
        font-size: 11px;
    }
</style>
</head>
<body >
  <svg id='svg' width="800" height="600" style="background-color: #efefef;">
   
  </svg>
  <script>
    // 定义画布位置
    var merge = { top: 60, bottom: 60, right: 60, left: 60 }
    var dataset = [10, 20, 30, 40, 50, 60, 70]
    var rectHeight = 30 // 矩形的高度

    // 定义比例尺
    // 线性比例尺
    var scaleLinear = d3.scaleLinear()
      .domain([0, d3.max(dataset)])
      .range([0, 250])

    // 定义序列比例尺
    var  ordinal = d3.scaleOrdinal()
      .domain(d3.range(0, dataset.length))
      .range(['red', 'green', 'blue', 'yellow', 'black'])


    var svg = d3.select('#svg')
    var g = svg.append('g')
                .attr('transfrom', 'translate('+merge.top+', '+merge.left+')')
    
    g.selectAll('rect')
      .data(dataset)
      .enter()
      .append('rect')
      .attr('x', 20)
      .attr('y', (d, i) => {
        return i * rectHeight + (i * 5)
      })
      .attr('width', (d, i) => {
        return scaleLinear(d)
      }) 
      .attr('height', rectHeight)
      .attr('fill', (d, i) => {
        return ordinal(i)
      })

    var xScale = d3.scaleLinear()
      .domain([0, d3.max(dataset)])
      .range([250, 0])

    var xAxis = d3.axisBottom(xScale)
      .ticks(6)
    g.append('g')
      .attr("class", 'axis')
      .attr("transform", "translate(20, "+(dataset.length * rectHeight+ 50)+")")// 设置画布的位置
      .call(xAxis)
  </script>
</body>
</html>